<script setup lang="ts">
import { onMounted, ref, watch, type PropType } from "vue";
import { ElDialog, ElForm, ElFormItem, ElInput, ElButton, ElCascader, type CascaderProps, ElInputNumber, type CascaderValue, type CascaderNodeValue, ElTreeSelect } from "element-plus";
import { SysDepartment } from "@/entity/SysDepartment";
import { OperationType } from "@/entity/OperationType";
import { AxiosError } from "axios";
import { ElMessage } from "element-plus";
import departmentService from "@/services/department.service";
import { Search, Refresh, Plus, Edit, Delete, View, Upload, Download, Share, Close } from "@element-plus/icons-vue";

const props = defineProps({
    visible: {
        type: Boolean,
        default: false,
    },
    id: {
        type: Number,
        require: false,
    },
    operation: {
        type: String,
        require: false,
    },
    parent: {
        type: Object as PropType<SysDepartment>,
        require: false,
    }
});

const emits = defineEmits(["update:visible"]);

const entity = ref(new SysDepartment());
const saveLoading = ref(false);

const showDialog = ref(false);

const treeProps: CascaderProps = {
    value: "id",
    label: "name",
    children: "children",
    checkStrictly: true,
};
const treeData = ref<SysDepartment[]>([]);

watch(
    () => props.visible,
    async (value) => {
        showDialog.value = value;
        if (showDialog.value == true) {
            if (props.operation == OperationType.CREATE) {
                create();
            } else if (props.operation == OperationType.EDIT) {
                edit();
            }
        }
    }
);

const load = async () => {
    try {
        if (props.id == null) {
            return;
        }
        const e = await departmentService.retrieve(props.id);
        entity.value = e;
    } catch (err) {
        if (err instanceof AxiosError) {
            const msg = err.response?.data?.message || err.message;
            ElMessage({ message: msg, type: "error" });
        }
        throw err;
    } finally {
    }
    await loadData();
};

const loadData = async () => {
    try {
        treeData.value = await departmentService.treeList();
    } catch (err) {
        if (err instanceof AxiosError) {
            const msg = err.response?.data?.message || err.message;
            ElMessage({ message: msg, type: "error" });
        }
        throw err;
    } finally {
    }
}

const create = async () => {
    entity.value = new SysDepartment();
    if (props.parent) {
        entity.value.parentId = props.parent.id;
    }
    await loadData();
}


const edit = async () => {
    await load();
}

const save = async () => {
    try {
        saveLoading.value = true;
        if (props.operation == OperationType.CREATE) {
            await departmentService.insert(entity.value);
        } else if (props.operation == OperationType.EDIT) {
            await departmentService.update(entity.value);
        }
        ElMessage({ message: "保存成功", type: "success" });
        emits("update:visible", false);
    } catch (err) {
        if (err instanceof AxiosError) {
            const msg = err.response?.data?.message || err.message;
            ElMessage({ message: msg, type: "error" });
        }
        throw err;
    } finally {
        saveLoading.value = false;
    }
}

onMounted(async () => {

});

const cancel = () => {
    emits("update:visible", false);
}

const closeDialog = () => {
    cancel();
};

const handleParentChange = (value: any) => {
    if (value == null || value == "") {
        entity.value.parentId = null;
    } else {
        entity.value.parentId = value;
    }
}
</script>

<template>
    <ElDialog v-model="showDialog" :width="500" @close="closeDialog()" title="部门详情">
        <ElForm v-model="entity" label-width="120px" class="form">
            <ElFormItem label="父级部门">
                <ElTreeSelect class="w-full" v-model="entity.parentId" :props="treeProps" :data="treeData" clearable
                    filterable check-strictly @change="handleParentChange"></ElTreeSelect>
            </ElFormItem>
            <ElFormItem label="编号">
                <ElInput v-model="entity.code"></ElInput>
            </ElFormItem>
            <ElFormItem label="名称">
                <ElInput v-model="entity.name"></ElInput>
            </ElFormItem>
            <ElFormItem label="顺序">
                <ElInputNumber class="w-full" v-model="entity.orderNo"></ElInputNumber>
            </ElFormItem>
            <ElFormItem label="描述">
                <ElInput v-model="entity.description"></ElInput>
            </ElFormItem>
        </ElForm>

        <template #footer>
            <div class="dialog-footer">
                <ElButton :loading="saveLoading" @click="cancel()">取消</ElButton>
                <ElButton type="primary" :loading="saveLoading" @click="save()">保存</ElButton>
            </div>
        </template>
    </ElDialog>
</template>

<style scoped>
.form {
    max-width: 460px;
}
</style>